// import React from "react";
import React from "./react";

let timer;
class Counter5 extends React.Component{
    constructor(props){
      super(props)
      this.state={
        messages:[]
      }
      this.wrapper = React.createRef()
    }

    addMessage =()=>{
      this.setState({
        messages: [this.state.messages.length,...this.state.messages]
      })
    }
    componentDidMount(){
      timer = window.setInterval(this.addMessage,1000)
    }
    componentWillUnmount(){
      clearInterval(timer)
    }

    getSnapshotBeforeUpdate(){ // 获取dom更新前快照 并传值给componentDidUpdate
      return{
        prevScrollTop: this.wrapper.current.scrollTop,
        prevScrollHeight:this.wrapper.current.scrollHeight
      }
    }
    componentDidUpdate(pervProps, pervState, {prevScrollHeight,prevScrollTop}) {
      //当前向上卷去的高度加上增加的内容高度
      this.wrapper.current.scrollTop = prevScrollTop + (this.wrapper.current.scrollHeight - prevScrollHeight);
  }
  
    render(){
      let style = {
        height: '100px',
        width: '200px',
        border: '1px solid red',
        overflow: 'auto'
    }
    return (
        <div style={style} ref={this.wrapper} >
            {this.state.messages.map((message, index) => (
                <div key={index}>{message}</div>
            ))}
        </div>
    );
    }
}

export default Counter5